<template>
  <div>
    <div class="breadcrumb">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/main' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>管理员管理</el-breadcrumb-item>
        <el-breadcrumb-item>系统管理员列表</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <el-card class="box-card">
         <el-row :gutter="20">
           <el-col :span="9">
              <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable  @clear="getAdminList">
                  <el-button slot="append" icon="el-icon-search" @click="getAdminList"></el-button>
              </el-input>
           </el-col>
           <el-col :span="4">
              <el-button type="primary" @click="dialogVisible = true">添加管理员</el-button>
           </el-col>
         </el-row>

     <div>
       <el-dialog title="添加系统管理员" :visible.sync="dialogVisible" width="50%" @close="closeDialog">
         <el-form :model="addAdminModel" :rules="rules" ref="addAdminRef" label-width="100px" class="demo-ruleForm">
           <el-form-item label="用户名" prop="name">
             <el-input v-model="addAdminModel.name"></el-input>
           </el-form-item>
           <el-form-item label="性别" prop="sex">
             <el-radio v-model="addAdminModel.sex" label="男">男</el-radio>
             <el-radio v-model="addAdminModel.sex" label="女">女</el-radio>
             <!-- <el-input v-model="addAdminModel.sex"></el-input> -->
           </el-form-item>
           <el-form-item label="密码" prop="password">
             <el-input v-model="addAdminModel.password" type="password"></el-input>
           </el-form-item>
           <el-form-item label="密码确认" prop="password2">
             <el-input v-model="addAdminModel.password2" type="password"></el-input>
           </el-form-item>
           <el-form-item label="身份证号" prop="idNumber">
             <el-input v-model="addAdminModel.idNumber" type="password"></el-input>
           </el-form-item>
           <el-form-item label="电话" prop="phone">
             <el-input v-model="addAdminModel.phone"></el-input>
           </el-form-item>
           <el-form-item label="邮箱" prop="email">
             <el-input v-model="addAdminModel.email"></el-input>
           </el-form-item>
         </el-form>
         <span slot="footer" class="dialog-footer">
           <el-button @click="dialogVisible = false">取 消</el-button>
           <el-button type="primary" @click="addAdminBtn">确 定</el-button>
         </span>
       </el-dialog>
     </div>
     </el-card>

     <div>
       <!-- 定义修改页面 当对话框关闭时,将表格数据重置-->
       <el-dialog title="修改系统管理员信息" :visible.sync="updateDialogVisible" width="50%" @close="closeUpdateDialog">
         <!-- 定义管理员提交表单数据-->
         <el-form :model="updateAdminModel" :rules="rules" ref="updateAdminRef" label-width="100px">
           <el-form-item label="用户名" prop="name">
             <el-input v-model="updateAdminModel.name"  disabled ></el-input>
           </el-form-item>
           <el-form-item label="性别" prop="sex">
             <el-input v-model="updateAdminModel.sex"  disabled ></el-input>
           </el-form-item>
           <el-form-item label="身份证号" prop="phone">
             <el-input v-model="updateAdminModel.phone"></el-input>
           </el-form-item>
           <el-form-item label="邮箱" prop="email">
             <el-input v-model="updateAdminModel.email"></el-input>
           </el-form-item>
         </el-form>
         <span slot="footer" class="dialog-footer">
           <el-button @click="updateDialogVisible = false" >取 消</el-button>
           <el-button type="primary" @click="updateAdmin">确 定</el-button>
         </span>
       </el-dialog>
     </div>
     <div class="table">
         <el-table :data="adminInfo" border stripe>
          <el-table-column type="id" label="编号"></el-table-column>
          <el-table-column type="name" label="姓名"></el-table-column>
          <el-table-column type="sex" label="性别"></el-table-column>
          <el-table-column type="idNumber" label="身份证号"></el-table-column>
          <el-table-column type="phone" label="手机号"></el-table-column>
          <el-table-column type="email" label="邮箱"></el-table-column>
          <el-table-column type="appoint" label="任命时间"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
               <el-button type="primary" icon="el-icon-edit" size="small" @click="updateAdminBtn(scope.row)"></el-button>
               <el-button type="danger" icon="el-icon-delete" size="small" @click="deleteAdmin(scope.row)"></el-button>
            </template>
          </el-table-column>
        </el-table>
    </div>
  </div>

</template>

<script>
  export default {
      data() {
        const checkEmail = (rule, value, callback) => {
          //定义邮箱的正则表达式  JS中用/来表示正则表达式的开始和结束
          const emailRege = /^[a-zA-Z0-9-_]+@[a-zA-Z0-9-_]+\.[a-zA-Z0-9-_]+$/
          //正则表达式语法校验  test(xx) 校验成功 返回true  校验失败返回false
          if (emailRege.test(value)) {
            //表示邮箱合法 正确返回
            return callback()
          }
          callback(new Error('请填写正确的邮箱地址'))
        }

        //校验身份证号的邮箱规则
        const checkIdNumber = (rule, value, callback) => {
          //定义校验身份证号的正则语法
          const idnumberRege =/^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
          if (idnumberRege.test(value)) {
            return callback()
          }
          callback(new Error('请填写正确的身份证号'))
        }

        //校验手机号的邮箱规则
        const checkPhone = (rule, value, callback) => {
          //定义校验手机号的正则语法
          const phoneRege = /^1[3456789][0-9]{9}$/
          if (phoneRege.test(value)) {
            return callback()
          }
          callback(new Error('请填写正确的手机号'))
        }

        const checkPassword = (rule, value, callback) => {
          if(this.addUserModel.password !== value) return callback(new Error('2次密码输入不一致'))
          //否则校验成功
          callback()
        }
        return {
         adminInfo:[],
          queryInfo:{},
          addAdmin:{},
          queryInfo: {
            query: '',
            pageNum: 1,
            pageSize: 5
          },
          addAdminModel : {
            name : '',
            password : '',
            password2 : '',
            idNumber : '',
            phone : '',
            email : ''
          },
          updateAdminModel : {
            id : '',
            name : '',
            idNumber : '',
            phone : '',
            email : '',
            appoint : ''
          },
          pickerOptions: {
            shortcuts: [{
              text: '今天',
              onClick(picker) {
                picker.$emit('pick', new Date());
              }
            }, {
              text: '昨天',
              onClick(picker) {
                const date = new Date();
                date.setTime(date.getTime() - 3600 * 1000 * 24);
                picker.$emit('pick', date);
              }
            }, {
              text: '一周前',
              onClick(picker) {
                const date = new Date();
                date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
                picker.$emit('pick', date);
              }
            }]
          },
          dialogVisible : false,
          updateDialogVisible : false,
          rules: {
            name: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 2, max: 30, message: '长度在 3 到 30 个字符', trigger: 'blur' }
                  ],
            password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 3, max: 30, message: '长度在 3 到 30 个字符', trigger: 'blur' }
                  ],
            password2: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 3, max: 30, message: '长度在 3 到 30 个字符', trigger: 'blur' },
                    { validator: checkPassword , trigger: 'blur' }
                  ],
            idNumber: [
                    { required: true, message: '请输入身份证号', trigger: 'blur' },
                    { min: 3, max: 30, message: '长度在 3 到 30 个字符', trigger: 'blur' },
                    { validator: checkIdNumber, trigger: 'blur' }
                  ],
            phone: [
                    { required: true, message: '请输入手机号', trigger: 'blur' },
                    { min: 3, max: 30, message: '长度在 3 到 30 个字符', trigger: 'blur' },
                    { validator: checkPhone , trigger: 'blur' }
                  ],
            email: [
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    { min: 3, max: 30, message: '长度在 3 到 30 个字符', trigger: 'blur' },
                    { validator: checkEmail , trigger: 'blur' }
                  ]
          },
        }
      },
      methods:{
        async getAdminList(){
          const {data: result} = await this.$http.get('/admin/list',{
             params: this.queryInfo
          })
          if(result.status !== 200) return this.$message.error("用户列表查询失败")
          this.adminInfo = result.data.rows
        },
        closeDialog(){
          //重置表格数据
          this.$refs.addAdminRef.resetFields()
        },
        closeUpdateDialog(){
          //重置表格数据
          this.$refs.updateAdminRef.resetFields()
        },
        addAdminBtn(){
          this.$refs.addAdminRef.validate(async valid => {
            //如果校验失败 则停止数据
            if(!valid) return
            const {data: result} = await this.$http.post('/admin/addAdmin',this.addAdminrModel)
            if(result.status !== 200) return this.$message.error("系统管理员新增失败")
            this.$message.success("系统管理员新增成功")
            //关闭对话框
            this.dialogVisible = false
            //重新获取用户列表
            this.getAdminList()
          })
        },
        async deleteAdmin(admin){
          const result =  await this.$confirm('此操作将永久删除 '+admin.name+', 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                  }).catch(error => error)

          //如果确认  confirm  如果取消 cancel
          if(result !== 'confirm'){
              return this.$message.info("删除取消")
          }
          const {data: result2} = await this.$http.delete(`/admin/${admin.id}`)
          if(result2.status !== 200) return this.$message.error("删除失败")
          this.$message.success("删除成功")
          //重新加载 数据
          this.getAdminList()
        },
        async updateAdminBtn(adminInfo){
          this.updateDialogVisible = true
          const {data: result} = await this.$http.get("/admin/"+adminInfo.id)
          if(result.status !== 200) return this.$message.error("用户查询失败")
          this.updateAdminModel = result.data
        },
        updateAdmin(){
         //1.预校验数据
         this.$refs.updateadminRef.validate(async valid => {
            if(!valid)  return this.$message.error("表单验证没有通过")
            //根据接口文档要求封装数据
            let admin = {}
            admin.id = this.updateAdminModel.id
            admin.phone = this.updateAdminModel.phone
            admin.email = this.updateAdminModel.email
            const {data: result} = await this.$http.put(`/admin/updateAdmin`,admin)
            if(result.status !== 200) return this.$message.error("用户修改失败")
            this.$message.success("用户更新成功")
            this.updateDialogVisible = false
            this.getAdminList()
         })
      }
     },
     created() {
       this.getAdminList()
     }
   }
</script>

<style>
  .breadcrumb{
    margin-bottom: 20px;
  }
  .operation{
    margin-bottom: 20px;
  }
  .table{
    white-space: nowrap;
  }
</style>
